// pages/blog-edit/blog-edit.js
const qiniuUploader = require("../../utils/qiniuUploader.js");
let regeneratorRuntime = require("../../utils/regenerator-runtime/runtime");
// import formatTime from '../../utils/qiniuUploader.js'
var app = getApp()
import {
  batchUpload
} from '../../utils/imgupload.js'
// 输入文字最大的个数
const MAX_WORDS_NUM = 140
// 最大上传图片数量
const MAX_IMG_NUM = 9
const db = wx.cloud.database()
// 输入文字内容
let content = ''
let userInfo = {}
let token = ''
var imgList = []
let user_id = ''
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 输入的文字个数
    wordsNum: 0,
    footerBottom: 0,
    images: [],
    selectPhoto: true, // 添加图片元素是否显示
    showImage: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    userInfo = options
  },

  onInput(event) {
    // console.log(event.detail.value)
    let wordsNum = event.detail.value.length
    if (wordsNum >= MAX_WORDS_NUM) {
      wordsNum = `最大字数为${MAX_WORDS_NUM}`
    }
    this.setData({
      wordsNum
    })
    content = event.detail.value
  },

  onFocus(event) {
    console.log(event)
    this.setData({
      footerBottom: event.detail.height
    })
  },

  onBlur() {
    this.setData({
      footerBottom: 0,
    })
  },

  onChooseImage() {
    // 还能再选几张图片
    let max = MAX_IMG_NUM - this.data.images.length
    wx.chooseImage({
      count: max,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log(res)
        this.setData({
          images: this.data.images.concat(res.tempFilePaths)
        })
        console.log(this.data.images)
        // 还能再选几张图片
        max = MAX_IMG_NUM - this.data.images.length
        this.setData({
          selectPhoto: max <= 0 ? false : true
        })
      },
    })
  },

  getToken() {
    wx.request({
      url: 'http://127.0.0.1:8000/token/',
      success: ((res) => {
        token = res.data.uptoken
        console.log(token)
        this.uploadQiniu()
      })
    })
  },

  uploadQiniu() {
    let imageList = this.data.images;
    var state = 0; //state记录当前已经上传到第几张图片
    new Promise(function(resolve, reject) {
      for (var i = 0; i < imageList.length; i++) {
        qiniuUploader.upload(imageList[i], (res) => {
          state++;
          imgList.push('http://' + res.imageURL);
          console.log(state)
          if (state == imageList.length) {
            resolve(imgList);
          }
        }, (error) => {
          reject('error');
          console.log('error: ' + error);
        }, {
          uploadURL: 'https://upload.qiniup.com',
          domain: 'li11.wang/',
          uptoken: token //从后台请求回来的token
        })
      }
    }).then((imgList) => {
      console.log(this.data.images)
      
      this.sendMessage()
    })

    // wx.uploadFile({
    //   url: 'https://upload.qiniup.com',
    //   name: 'file',
    //   filePath: tempFilePaths[0],
    //   header: {
    //     "Content-Type": "multipart/form-data"
    //   },
    //   formData: {
    //     token,
    //   },
    //   success: (res)=> {
    //     let data = JSON.parse(res.data)
    //     console.log(data.key)
    //     // to do ...
    //   },
    //   fail: function (res) {
    //     console.log(res)
    //   }
    // })
  },

  onDelImage(event) {
    this.data.images.splice(event.target.dataset.index, 1)
    this.setData({
      images: this.data.images
    })
    if (this.data.images.length == MAX_IMG_NUM - 1) {
      this.setData({
        selectPhoto: true,
      })
    }
  },

  onPreviewImage(event) {
    wx.previewImage({
      urls: this.data.images,
      current: event.target.dataset.imgsrc,
    })
  },


  sendMessage() {
    // let user_id = ''
    // wx.getStorage({
    //   key: 'user_id',
    //   success: (res) => {
    //     user_id = res.data
    //     console.log(user_id)
    //   },
    // })
    console.log(this.data.images)
    const tempFilePaths = this.data.images
    let file = tempFilePaths[0];
    let params = {
      uploadUrl: 'http://127.0.0.1:8000/upload_images/', // 图片上传接口
      imgPaths: tempFilePaths
    }
    batchUpload(params, batchUpload, (res) => {
      console.log(res)
      let showImage = this.data.showImage
      showImage = res.imgPaths
      this.setData({
        showImage
      }, () => {
        let msg = '成功上传' + res.successNum + "张,失败" + res.failNum + "张"
        wx.showToast({
          title: msg
        })
      })
      console.log(userInfo)
      console.log(user_id)
      wx.request({
        url: 'http://127.0.0.1:8000/blog_info/',
        method: 'POST',
        data: {
          user_id,
          content,
          showImage: showImage,
          nickname: userInfo.nickName,
          avatarurl: userInfo.avatarUrl,
        },
        success: ((res) => {
          console.log(res)
          wx.hideLoading()
          wx.showToast({
            title: '发布成功',
          })
          // 返回blog页面，并且刷新
          wx.navigateBack()
          const pages = getCurrentPages()
          // console.log(pages)
          const prevPage = pages[pages.length - 2]
          prevPage.onPullDownRefresh()
          // wx.navigateBack()
        })
      })
    })
  },

  async send() {

    wx.getStorage({
        key: 'user_id',
        success: (res) => {
          user_id = res.data
          console.log(user_id)
        },
      })

    if (content.trim() === '') {
      wx.showModal({
        title: '请输入内容',
        content: '',
      })
      return
    }

    wx.showLoading({
      title: '正在发布...',
      mask: true,
    })

    await this.getToken()

    // console.log(this.data.images)
    // let user_id = ''
    // wx.getStorage({
    //   key: 'user_id',
    //   success: (res) => {
    //     // console.log(res.data)
    //     user_id = res.data
    //     console.log(user_id)
    //   },
    // })
    // const tempFilePaths = this.data.images
    // let file = tempFilePaths[0];
    // let params = {
    //   uploadUrl: 'http://127.0.0.1:8000/upload_images/', // 图片上传接口
    //   imgPaths: tempFilePaths
    // }
    // batchUpload(params, batchUpload, (res) => {
    //   let showImage = this.data.showImage
    //   showImage = res.imgPaths
    //   this.setData({
    //     showImage
    //   }, () => {
    //     let msg = '成功上传' + res.successNum + "张,失败" + res.failNum + "张"
    //     wx.showToast({
    //       title: msg
    //     })
    //   })
    //   console.log(userInfo)
    //   wx.request({
    //     url: 'http://127.0.0.1:8000/blog_info/',
    //     method: 'POST',
    //     data: {
    //       user_id,
    //       content,
    //       showImage: showImage,
    //       nickname: userInfo.nickName,
    //       avatarurl: userInfo.avatarUrl,
    //     },
    //     success: ((res) => {
    //       console.log(res)
    //       wx.hideLoading()
    //       wx.showToast({
    //         title: '发布成功',
    //       })
    //       // wx.navigateBack()
    //     })
    //   })
    // })



    // 存入到云数据库
    // Promise.all(promiseArr).then(() => {
    //   db.collection('blog').add({
    //     data: {
    //       ...userInfo,
    //       content,
    //       img: fileIds,
    //       createTime: db.serverDate(), //服务端时间
    //     }
    //   }).then(() => {
    //     wx.hideLoading()
    //     wx.showToast({
    //       title: '发布成功',
    //     })

    //     // 返回blog页面，并且刷新
    //     wx.navigateBack()
    //     const pages = getCurrentPages()
    //     // console.log(pages)
    //     const prevPage = pages[pages.length - 2]
    //     prevPage.onPullDownRefresh()
    //   })
    // }).catch(() => {
    //   wx.hideLoading()
    //   wx.showToast({
    //     title: '发布失败，请重试',
    //   })
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})